import { login, logout, getUserByToken } from "@/api/login";
import { getToken, setToken, removeToken } from "@/utils/cookie";
import http from '@/utils/http'
import { setSessionStorage, getSessionStorage, removeSessionStorage} from '@/utils/storage'

const USER_ID = 'USER_ID'

const user = {

    state: {
        token: getToken(),
        detail: {
            id: null,
            account: null,
            password: null,
            salt: null,
            mobile: null,
            email: null,
            realName: null,
            avatar: null,
            sex: null,
            status: null,
            loginCount: null,
            lastLoginTime: null,
            lastLoginIp: null,
            isAdmin: null,
            ctime: null,
            utime: null,
            company: null,
            department: null,
            roles: null,
            groups: null,
            permissions: null,
            token: null,
            expires: null,
            ip: null,
            ipCity: null,
            identify: null
        },
        location: {
            status: null,
            info: null,
            infocode: null,
            province: null,
            city: null,
            adcode: null,
            rectangle: null
        }
    },
    mutations: {
        SET_TOKEN: (state, token) => {
            state.token = token
        },
        SET_USER_DETAIL: (state, data) => {
            state.detail = data
        },
        CLEAR_USER_DETAIL: (state) => {
            state.detail = Object.assign({}, {
                id: null,
                account: null,
                password: null,
                salt: null,
                mobile: null,
                email: null,
                realName: null,
                avatar: null,
                sex: null,
                status: null,
                loginCount: null,
                lastLoginTime: null,
                lastLoginIp: null,
                isAdmin: null,
                ctime: null,
                utime: null,
                company: null,
                department: null,
                roles: null,
                groups: null,
                permissions: null,
                token: null,
                expires: null,
                ip: null,
                ipCity: null,
                identify: null
            })
        },
        SET_IP_LOCATION: (state, location) => {
            state.location = Object.assign({}, location)
        }

    },
    actions: {
        // 账号登录（支持用户名，手机号，邮箱）
        Login({ commit, state }, userInfo) {
            return new Promise((resolve, reject) => {
                login(userInfo.account.trim(), userInfo.password).then(response => {
                    const data = response.data.data
                    if(data != undefined && response.data.status) {
                        commit('SET_TOKEN', data.token)
                        setSessionStorage(USER_ID, data.id)
                    }
                    resolve(response)
                }).catch(() => {
                    reject({status: false, msg: '登录发生异常，可能服务器未开，请联系管理员'})
                })
            })
        },

        GetUser({ dispatch, commit, state }, token) {
            return new Promise((resolve, reject) => {
                if(token) {
                    getUserByToken(token).then((response) => {
                        const data = response.data
                        if(data) {
                            commit('SET_USER_DETAIL', data)
                            resolve(response)
                        } else {
                            dispatch('FedLogOut').then(() => {})
                            resolve({status: false, message: '登录过期，请重新登录'})
                        }

                    }).catch((error) => {
                        reject(error)
                    })
                } else {
                    reject()
                }
            })
        },

        // 后端登出
        LogOut({ commit, state }) {
            return new Promise((resolve, reject) => {
                logout(state.token).then(() => {
                    removeSessionStorage(USER_ID)
                    removeToken()
                    resolve()
                }).catch(() => {
                    reject()
                })
            })
        },

        // 前端登出
        FedLogOut({ commit, state }) {
            return new Promise((resolve, reject) => {
                commit('SET_TOKEN', '')
                commit('CLEAR_USER_DETAIL')
                removeSessionStorage(USER_ID)
                removeToken()
                resolve()
            })
        },

        //获取登录用户的ip所在地理位置
        GetIpCity({ commit, state }) {
            return new Promise((resolve, reject) => {
                //调用高德Web API 进行IP定位
                http({
                    url: 'http://restapi.amap.com/v3/ip?key=2b7d6cf58cefb5511c218cf37d776ba0&ip=113.109.162.18',
                    method: 'get'
                }).then(response => {
                    const data = response.data
                    commit('SET_IP_LOCATION', data)
                })
            })
        }
    }

}

export default user
